package com.ruoyi.web.controller.business.goods.factory;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ruoyi.business.base.PageParam;
import com.ruoyi.business.goods.domain.JbCropVariety;
import com.ruoyi.business.goods.domain.vo.JbCropVarietyVo;
import com.ruoyi.business.goods.service.JbCropVarietyService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.core.JoController;
import com.ruoyi.web.core.tool.ColumnUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务 作物 工厂
 *
 * @author Jyl
 */
@Component
public class JbCropVarietyFactory extends JoController
{
    @Autowired
    private JbCropVarietyService jbCropVarietyService;

    public Map<String, Long> dict()
    {
        Map<String, Long> map = new HashMap<>();
        List<JbCropVariety> list = jbCropVarietyService.list();
        for (JbCropVariety jbCropVariety : list)
        {
            map.put(jbCropVariety.getCropName(), jbCropVariety.getId());
        }
        return map;
    }

    public IPage page(PageParam page, JbCropVariety jbCropVariety) throws InvocationTargetException,
            NoSuchMethodException, IllegalAccessException
    {
        LambdaQueryWrapper<JbCropVariety> select = new LambdaQueryWrapper<>();

        select.like(StringUtils.isNotEmpty(jbCropVariety.getCommonOccurMonth()), JbCropVariety::getCommonOccurMonth,
                        jbCropVariety.getCommonOccurMonth())
                .like(StringUtils.isNotEmpty(jbCropVariety.getCommonRegion()), JbCropVariety::getCommonRegion,
                        jbCropVariety.getCommonRegion())
                .like(StringUtils.isNotEmpty(jbCropVariety.getCommonTarget()), JbCropVariety::getCommonTarget,
                        jbCropVariety.getCommonTarget())
                .and(StringUtils.isNotEmpty(page.getKeyword()), e -> e
                        .like(JbCropVariety::getCropCode, page.getKeyword())
                        .or().like(JbCropVariety::getCropName, page.getKeyword()))
                .orderByDesc(JbCropVariety::getId)
        ;

        //数据映射 createBy 映射 createName
        IPage<JbCropVarietyVo> vo = convert(jbCropVarietyService.page(page.b(), select), JbCropVarietyVo.class);
        List<Long> ids = ids(vo, ColumnUtil.F(JbCropVarietyVo::getCreateBy));
        Map map = kv(
                ColumnUtil.F(SysUser::getUserId),
                ColumnUtil.F(SysUser::getNickName),
                userController.listByIds(ids)
        );
        toKey(vo, map,
                ColumnUtil.F(JbCropVarietyVo::getCreateBy),
                ColumnUtil.F(JbCropVarietyVo::getCreateName)
        );

        return vo;
    }
}
